package emby.stmt;

import emby.EmbyRuntime;
import emby.expr.Expression;
import emby.lang.Block;
import emby.lang.Scope;
import emby.writer.IEmbyCodifier;

public class IfElse extends Statement{

	private static final long serialVersionUID = 3457822227839152581L;
	Expression condition;
	Block ifbody;
	Block elsebody;
	public IfElse(Expression _condition, Block if_body, Block else_body){
		condition = _condition;
		ifbody = if_body;
		elsebody = else_body;
	}

	private boolean isConditionTrue(Scope s){
		Object o = condition.eval(s);
		if( o==null) return false;
		if( o==Boolean.FALSE) return false;
		if( o instanceof Number) return ((Number)o).doubleValue()!=0;
		return true;
	}

	/**
	 * Always returns null UNLESS there was a return statement in the block.
	 */
	@Override
	public Object eval(Scope s) {
		//Scope subscope = new Scope(s);

		boolean isTrue = isConditionTrue(s);
		if(EmbyRuntime.echo){
			emby.util.Print.println("Evaluating if statement. Condition: "+condition+ "("+isTrue+")");
		}

		if( isTrue){
			Object returnVal = ifbody.eval(s);
			if(returnVal!=null){
				return returnVal;
			}
		}else{
			Object returnVal = elsebody.eval(s);
			if(returnVal!=null){
				return returnVal;
			}
		}
		return null;
	}

	public String toString(){
		if( condition ==null){
			return "{IfElse_stmt}";
		}
		return "IfElse("+condition+")";
	}
	
	public void codify(IEmbyCodifier ec){
		ec.ifelse(condition, ifbody, elsebody);
	}
}
